<template>
  <div class="ask-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title"> Question</h1>
        <p class="page-description">Share your questions and get professional answers</p>
      </div>
    </div>

    <!-- 提问表单 -->
    <div class="ask-form-container">
      <el-form
        ref="askFormRef"
        :model="askForm"
        :rules="askRules"
        label-position="top"
        class="ask-form"
      >
        <!-- 问题标题 -->
        <el-form-item label="Problem Title" prop="title" class="form-item">
          <el-input
            v-model="askForm.title"
            placeholder="Please enter a question title that succinctly and clearly describes your problem"
            size="large"
            maxlength="500"
            show-word-limit
            class="title-input"
          />
          <div class="form-tip">
            A good title can help you get better answers
          </div>
        </el-form-item>

        <!-- 问题描述 -->
        <el-form-item label="Problem description" prop="content" class="form-item">
          <el-input
            v-model="askForm.content"
            type="textarea"
            placeholder="Provide a detailed description of your problem, including background information, specific circumstances..."
            :rows="8"
            maxlength="10000"
            show-word-limit
            class="content-textarea"
          />
          <div class="form-tip">
            A detailed description can help the respondent better understand your question
          </div>
        </el-form-item>

        <!-- 话题标签 -->
        <el-form-item label="Related topics" class="form-item">
          <el-select
            v-model="askForm.topicIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="Search and select relevant topics"
            :remote-method="searchTopicsHandler"
            :loading="topicLoading"
            size="large"
            class="topic-select"
          >
            <el-option
              v-for="topic in topicOptions"
              :key="topic.id"
              :label="topic.name"
              :value="topic.id"
            >
              <div class="topic-option">
                <span class="topic-name">{{ topic.name }}</span>
                <span class="topic-desc">{{ topic.description }}</span>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">
            Choosing the right topic can help more people in related fields see your problem
          </div>
        </el-form-item>

        <!-- 匿名选项 -->
        <el-form-item class="form-item">
          <el-checkbox v-model="askForm.isAnonymous">
            Anonymous Questions
          </el-checkbox>
          <div class="form-tip">
            When asked anonymously, other users will not be able to see your personal information
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="form-actions">
          <el-button @click="handleCancel" size="large">
            Cancel
          </el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
            size="large"
          >
            Publish Question
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {createQuestion} from '@/api/question'
import {searchTopics} from '@/api/topic'

const router = useRouter()

// 表单引用
const askFormRef = ref()
// 响应式数据
const submitting = ref(false)
const topicLoading = ref(false)
const topicOptions = ref([])

// 表单数据
const askForm = reactive({
  title: '',
  content: '',
  topicIds: [],
  isAnonymous: false
})

// 表单验证规则
const askRules = {
  title: [
    { required: true, message: '请输入问题标题', trigger: 'blur' },
    { min: 5, message: '标题至少5个字符', trigger: 'blur' },
    { max: 500, message: '标题不能超过500个字符', trigger: 'blur' }
  ],
  content: [
    { max: 10000, message: '描述不能超过10000个字符', trigger: 'blur' }
  ]
}

// 搜索话题
const searchTopicsHandler = async (query) => {
  if (!query || query.trim().length === 0) {
    topicOptions.value = []
    return
  }

  topicLoading.value = true

  try {
    const response = await searchTopics({
      keyword: query.trim(),
      limit: 15
    })

    if (response.code === 200) {
      topicOptions.value = response.data || []
    } else {
      topicOptions.value = []
      console.error('搜索话题失败:', response.message)
    }
  } catch (error) {
    console.error('搜索话题失败:', error)
    topicOptions.value = []
    ElMessage.error('搜索话题失败')
  } finally {
    topicLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await askFormRef.value.validate()

    submitting.value = true

    // 调用创建问题API
    const response = await createQuestion({
      title: askForm.title,
      content: askForm.content,
      topicIds: askForm.topicIds,
      isAnonymous: askForm.isAnonymous
    })

    if (response.code === 200) {
      ElMessage.success('问题发布成功')
      // 跳转到问题详情页
      router.push(`/question/${response.data.id}`)
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布问题失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('发布失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.ask-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 32px 0;
  border-bottom: 1px solid $border-light;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: $text-color;
  margin: 0 0 12px 0;
}

.page-description {
  font-size: 16px;
  color: $text-secondary;
  margin: 0;
}

.ask-form-container {
  background: $background-color;
  border-radius: $border-radius-large;
  padding: 40px;
  box-shadow: $shadow-light;
}

.ask-form {
  .form-item {
    margin-bottom: 32px;

    :deep(.el-form-item__label) {
      font-size: 16px;
      font-weight: 500;
      color: $text-color;
      margin-bottom: 12px;
    }
  }

  .form-tip {
    margin-top: 8px;
    font-size: 13px;
    color: $text-light;
    line-height: 1.4;
  }

  .title-input {
    :deep(.el-input__inner) {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .content-textarea {
    :deep(.el-textarea__inner) {
      font-size: 15px;
      line-height: 1.6;
      resize: vertical;
    }
  }

  .topic-select {
    width: 100%;
  }

  .topic-option {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .topic-name {
      font-size: 14px;
      color: $text-color;
      font-weight: 500;
    }

    .topic-desc {
      font-size: 12px;
      color: $text-secondary;
    }
  }

  .form-actions {
    margin-top: 40px;
    text-align: right;

    .el-button {
      padding: 12px 32px;
      font-size: 15px;
      margin-left: 16px;
    }
  }
}

:deep(.el-checkbox) {
  .el-checkbox__label {
    font-size: 15px;
    color: $text-color;
  }
}
</style>
